In Java’s Object-Oriented Programming (OOP), the relationship between a superclass and a subclass is established through inheritance.
Superclass: Also known as the parent class or base class, it is the class from which a subclass inherits features. It can be any class that provides members (fields, methods, and nested classes) to other classes.
Subclass: Also known as the child class or derived class, it is the class that inherits features from the superclass. A subclass can access all the members of the superclass.
Here’s an example of a superclass and subclass relationship in Java:
Example of using superclass and subclass
// Superclass
class Vehicle {
protected String brand = "Ford"; // Vehicle attribute
public void honk() { // Vehicle method
System.out.println("Tuut, tuut!");
}
}
// Subclass
public class Car extends Vehicle {
private String modelName = "Mustang"; // Car attribute
public static void main(String[] args) {
// Create a myCar object
Car myCar = new Car();
// Call the honk() method (from the Vehicle class) on the myCar object
myCar.honk();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
System.out.println(myCar.brand + " " + myCar.modelName);
}
}
Output
Tuut, tuut!
Ford Mustang
In this example, Car is a subclass that extends the Vehicle superclass. The Car class inherits the brand attribute and the honk() method from the Vehicle class.
The extends keyword is used to establish an is-a relationship between the superclass and the subclass. The subclass extends the superclass, indicating that it inherits all the members (fields and methods) of the superclass.
It’s important to note that if a superclass member is declared as private, it cannot be accessed directly by the subclass. In the example above, the brand attribute is declared as protected in the Vehicle superclass, which allows it to be accessed by the Car subclass.